home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 651 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.6 KB  |  52 lines

  1. Path: locutus.rchland.ibm.com!usenet
  2. From: pstaite@vnet.ibm.com
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Reading string from text file
  5. Date: 5 Jan 1996 15:27:28 GMT
  6. Organization: IBM OS/2 Device Driver Development  Rochester, MN
  7. Message-ID: <4cjg10$16vn@locutus.rchland.ibm.com>
  8. References: <4cie21$8vk@daily-planet.nodak.edu>
  9. Reply-To: pstaite@vnet.ibm.com
  10. NNTP-Posting-Host: warpone.rchland.ibm.com
  11. X-Newsreader: IBM NewsReader/2 v1.2
  12.  
  13. In <4cie21$8vk@daily-planet.nodak.edu>, dhill@badlands.NoDak.edu (Dale A Hill) writes:
  14. >Looking for code sample that searches a text file line by line, searches for 
  15. >a particular text string on each line...if it finds it, marks its 
  16. >location and extracts (reads) all data from beginning of line to the 
  17. >search string -1.  Any help would be greatly appreciated.
  18.  
  19. Too simple for words, so here's code (untested) :-)
  20.  
  21. #include<iostream.h>
  22. #include<fstream.h>
  23. #include<string.h>
  24.  
  25. const size_t maxbuf = 4096;
  26.  
  27. int main( int agrc, char* argv[] ) {
  28.     if( argc < 3 ) {
  29.         cerr << "Hey, give me a filename and a string!" << endl;
  30.         return -1; }
  31.     ifstream f( argv[ 1 ] );
  32.     if( ! f ) {
  33.         cerr << "Hey, couldn't open file: " << argv[ 1 ] << endl;
  34.         return -2; }
  35.     char* buf( new char[ maxbuf ] );
  36.     if( ! buf ) {
  37.         cerr << "Can't even get " << maxbuf << " bytes!" << endl;
  38.         return -3; }
  39.     while( f.getline( buf, maxbuf ) ) {
  40.         char* p( strstr( buf, argv[ 2 ] ) );
  41.         if( p ) {
  42.             *p = '\0';
  43.             cout << buf << endl; } }
  44.     delete[] buf;
  45.     return 0; }
  46.  
  47.  
  48.  
  49. Phil Staite, team OS/2
  50. internet: pstaite@vnet.ibm.com  internal: pstaite@rchland
  51.  
  52.